locals {
  ess_group_name             = "${var.asg_name}-asg-${random_uuid.main.result}"
  ess_configuration_name     = "${var.asg_name}-cfg-${random_uuid.main.result}"
  ess_instance_name          = "${var.asg_name}-instance-${random_uuid.main.result}"
  ess_lifecycle_hook_name    = "${var.asg_name}-hook-${random_uuid.main.result}"
  ess_scaling_rule_name      = "${var.asg_name}-rule-${random_uuid.main.result}"
  ess_scaling_alarm_name     = "${var.asg_name}-alarm-${random_uuid.main.result}"
  simple_rule_ari            = var.create_simple_rule == true ? alicloud_ess_scaling_rule.simple.0.ari : ""
  step_rule_ari              = var.create_step_rule == true ? alicloud_ess_scaling_rule.step.0.ari : ""
  target_tracking_rule_ari   = var.create_target_tracking_rule == true ? alicloud_ess_scaling_rule.target.0.ari : ""  
  default_alarm_task_setting = { period = 60, method = "Average", threshold = 0, comparison_operator = ">=", trigger_after : 3 }
  alarm_task_setting         = length(var.alarm_task_setting) > 0 ? var.alarm_task_setting : local.default_alarm_task_setting
}
resource "random_uuid" "main" {}

data "alicloud_regions" "main" {
    current = true
}

data "alicloud_account" "main" {}

resource "alicloud_ess_scaling_group" "main" {
  count                      = var.scaling_group_id == "" ? 1 : 0
  scaling_group_name         = local.ess_group_name
  max_size                   = var.asg_max_size
  min_size                   = var.asg_min_size
  default_cooldown           = var.asg_cooldown
  vswitch_ids                = var.asg_vswitch_id
  removal_policies           = var.asg_removal_policies
  db_instance_ids            = var.rds_instance_ids
  loadbalancer_ids           = var.slb_instance_ids
}
resource "alicloud_ess_scaling_configuration" "main" {
  count                      = var.create_scaling_configuration ? 1 : 0
  scaling_group_id           = var.scaling_group_id == "" ? alicloud_ess_scaling_group.main.0.id : var.scaling_group_id
  image_id                   = var.ecs_image
  instance_types             = var.ecs_instance_type
  security_group_ids         = var.ecs_sg_id
  instance_name              = local.ess_instance_name
  scaling_configuration_name = local.ess_configuration_name
  internet_charge_type       = var.ecs_internet_billing_type
  internet_max_bandwidth_in  = var.ecs_max_bandwidth_in
  internet_max_bandwidth_out = var.ecs_max_bandwidth_out
  system_disk_category       = var.ecs_disk_type
  system_disk_size           = var.ecs_disk_size
  enable                     = var.enable
  active                     = var.active
  key_name                   = var.ecs_key_name
  role_name                  = var.role_name
  force_delete               = var.force_delete
  tags                       = var.tags
  dynamic "data_disk" {
    for_each = var.ecs_data_disks
    content {
      delete_with_instance   = lookup(data_disk.value, "delete_with_instance", null)
      snapshot_id            = lookup(data_disk.value, "snapshot_id", null)
      size                   = lookup(data_disk.value, "size", null)
      category               = lookup(data_disk.value, "category", null)
    }
  }
  user_data                  = <<HEREDOC
#!/bin/sh 
set -x
export OSSBUCKET_TERRAFORM="${var.userdata_TERRAFORM_OSSBUCKET}"
export HOME="/opt"
export endpoint="oss-cn-hongkong-internal.aliyuncs.com"
export accessKeyID=$(curl -s http://100.100.100.200/latest/meta-data/Ram/security-credentials/${var.role_name}|grep AccessKeyId |awk -F\" '{print $4}')
export accessKeySecret=$(curl -s http://100.100.100.200/latest/meta-data/Ram/security-credentials/${var.role_name}|grep AccessKeySecret |awk -F\" '{print $4}')
export stsToken=$(curl -s http://100.100.100.200/latest/meta-data/Ram/security-credentials/${var.role_name}|grep SecurityToken |awk -F\" '{print $4}')

apt-get -y update
apt-get -y install python-pip git software-properties-common
pip install --upgrade pip
pip install ansible==2.7.0
curl -o /usr/local/bin/ossutil http://gosspublic.alicdn.com/ossutil/1.6.9/ossutil64  
chmod +x /usr/local/bin/ossutil                          

ossutil config -e $${endpoint} -i $${accessKeyID} -k $${accessKeySecret} -t $${stsToken} 
ossutil cp -r oss://$${OSSBUCKET_TERRAFORM}/playbooks/public_keys $${HOME}/ops-terraform/playbooks/common --update
ossutil cp -r oss://$${OSSBUCKET_TERRAFORM}/playbooks/roles $${HOME}/ops-terraform/playbooks/common --update

mkdir $${HOME}/ops-terraform/playbooks/projects/
ln -s $${HOME}/ops-terraform/playbooks/common/roles $${HOME}/ops-terraform/playbooks/projects/roles

cp_chmod_exec () { 
    PLAYBOOK=$1
    echo $PLAYBOOK >> exec.txt
    ossutil cp oss://$${OSSBUCKET_TERRAFORM}/$PLAYBOOK $${HOME}/ops-terraform/$PLAYBOOK --update
    chmod 400 $${HOME}/ops-terraform/$PLAYBOOK
    ansible-playbook -v $${HOME}/ops-terraform/$PLAYBOOK
}    
list_playbooks="${join(" ", var.userdata_VAR_PLAYBOOKS)}"
for playbook in $${list_playbooks}
do
	cp_chmod_exec $playbook
done
HEREDOC
}

//简单伸缩规则
resource "alicloud_ess_scaling_rule" "simple" { //支持增加/减少指定数量的实例，或者将实例数量调整至指定值
  count                     = var.create_simple_rule ? 1 : 0
  scaling_rule_name         = local.ess_scaling_rule_name
  scaling_group_id          = var.scaling_group_id == "" ? alicloud_ess_scaling_group.main.0.id : var.scaling_group_id
  scaling_rule_type         = "SimpleScalingRule"
  adjustment_type           = var.asg_rule_adjustment_type
  adjustment_value          = var.asg_rule_adjustment_value
  cooldown                  = var.asg_rule_cooldown
}
//目标跟踪缩放规则
resource "alicloud_ess_scaling_rule" "target" {//目标追踪规则，会自动创建一项关联报警任务，只能由该报警任务执行目标追踪规则。禁用缩放则只有一条规则
  count                     = var.create_target_tracking_rule ? 1 : 0
  scaling_rule_name         = local.ess_scaling_rule_name
  scaling_group_id          = var.scaling_group_id == "" ? alicloud_ess_scaling_group.main.0.id : var.scaling_group_id
  scaling_rule_type         = "TargetTrackingScalingRule"
  estimated_instance_warmup = var.asg_rule_estimated_instance_warmup
  metric_name               = var.asg_rule_metric_name
  target_value              = var.asg_rule_target_value
  disable_scale_in          = var.asg_rule_disable_scale_in
}
//步进规则
resource "alicloud_ess_scaling_rule" "step" { //分段扩缩容策略,在简单规则的基础上增加了分步定义，可以通过一组策略集合精细地控制扩缩容。
  count                     = var.create_step_rule ? 1 : 0
  scaling_rule_name         = local.ess_scaling_rule_name
  scaling_group_id          = var.scaling_group_id == "" ? alicloud_ess_scaling_group.main.0.id : var.scaling_group_id
  scaling_rule_type         = "StepScalingRule"
  adjustment_type           = var.asg_rule_adjustment_type
  estimated_instance_warmup = var.asg_rule_estimated_instance_warmup
  dynamic "step_adjustment" {
    for_each                = var.asg_rule_step_adjustments
    content {
      metric_interval_lower_bound = lookup(step_adjustment.value, "lower_limit", null)
      metric_interval_upper_bound = lookup(step_adjustment.value, "upper_limit", null)
      scaling_adjustment          = lookup(step_adjustment.value, "adjustment_value", null)
    }
  }
}
resource "alicloud_ess_alarm" "main" { //根据告警项弹性伸缩实例
  count                     = var.create_lscaling_alarm ? 1 : 0
  name                      = local.ess_scaling_alarm_name
  description               = var.asg_alarm_description
  alarm_actions             = compact([local.simple_rule_ari, local.step_rule_ari, local.target_tracking_rule_ari])  
  scaling_group_id          = var.scaling_group_id == "" ? alicloud_ess_scaling_group.main.0.id : var.scaling_group_id
  enable                    = var.asg_alarm_enable
  metric_type               = var.asg_alarm_metric_type
  metric_name               = var.asg_alarm_metric_name
  period                    = lookup(local.alarm_task_setting, "period", null)
  statistics                = lookup(local.alarm_task_setting, "method", null)
  threshold                 = lookup(local.alarm_task_setting, "threshold", null)
  comparison_operator       = lookup(local.alarm_task_setting, "comparison_operator", null)
  evaluation_count          = lookup(local.alarm_task_setting, "trigger_after", null)  
}
resource "alicloud_mns_queue" "main"{
  name                      = local.ess_scaling_alarm_name
}
resource "alicloud_ess_notification" "main" {
  count                     = var.create_lscaling_notification ? 1 : 0
  scaling_group_id          = var.scaling_group_id == "" ? alicloud_ess_scaling_group.main.0.id : var.scaling_group_id
  notification_types        = var.asg_notification_type
  notification_arn          = "acs:ess:${data.alicloud_regions.main.regions.0.id}:${data.alicloud_account.main.id}:queue/${alicloud_mns_queue.main.name}"
}
resource "alicloud_ess_lifecycle_hook" "main" { //生命周期挂钩仅在弹性扩容或弹性收缩ECS实例时生效，手动添加或移出ECS实例时不受其影响
  count                     = var.create_lifecycle_hook ? 1 : 0
  scaling_group_id          = var.scaling_group_id == "" ? alicloud_ess_scaling_group.main.0.id : var.scaling_group_id
  name                      = local.ess_lifecycle_hook_name
  lifecycle_transition      = var.lifecycle_transition
  heartbeat_timeout         = var.heartbeat_timeout
  default_result            = var.hook_action_policy
  notification_arn          = var.notification_arn
  notification_metadata     = var.notification_metadata
}